﻿using System;
using Internal.KuiHuaBaoDian.Services.UI.Toggle;
using KuiHuaBaoDian.Services.UGUI.Layout;

namespace KuiHuaBaoDian.Services.UGUI.Toggle {

    /// <summary>
    /// 开关组服务句柄
    /// </summary>
    /// <typeparam name="TData">开关组服务管理的数据类型</typeparam>
    public class ToggleHandle<TData> : ToggleHandle {

        private IToggleHandleInternal Internal => this;

        /// <summary>
        /// 当前选中的数据
        /// </summary>
        public TData SelectedData {
            get {
                var layoutHandle = (LayoutHandle<ToggleData<TData>>)Internal.LayoutHandle;
                var toggleData = LayoutService.Instance.GetSelectedElementData(layoutHandle);
                return toggleData.Data;
            }
        }
    }

    /// <summary>
    /// 开关组服务句柄
    /// </summary>
    public class ToggleHandle : ILayoutHandle, IToggleHandleInternal {

        /// <summary>
        /// 当选择发生改变时
        /// </summary>
        public event IData<int>.ValueChangedDelegate SelectChanged {
            add {
                m_LayoutHandle.SelectChanged += value;
            }
            remove {
                m_LayoutHandle.SelectChanged -= value;
            }
        }

        /// <summary>
        /// 唯一ID
        /// </summary>
        public Guid GUID { get; } = Guid.NewGuid();

        /// <summary>
        /// 选中元素索引
        /// </summary>
        public ILayoutService.SelectedIndex SelectedIndex => m_LayoutHandle.SelectedIndex;

        /// <summary>
        /// 元素总数
        /// </summary>
        public int ElementCount => m_LayoutHandle.ElementCount;

        private LayoutHandle m_LayoutHandle;
        LayoutHandle IToggleHandleInternal.LayoutHandle {
            get => m_LayoutHandle;
            set => m_LayoutHandle = value;
        }

        /// <summary>
        /// 选中位于索引<paramref name="index"/>的元素
        /// </summary>
        /// <param name="index">元素索引</param>
        /// <param name="focus">是否跳转到选择项</param>
        /// <param name="sendCallback">是否发送通知</param>
        public void Select(int index, bool focus = false, bool sendCallback = true) => m_LayoutHandle.Select(index, focus, sendCallback);
    }
}

namespace Internal.KuiHuaBaoDian.Services.UI.Toggle {

    public interface IToggleHandleInternal {

        LayoutHandle LayoutHandle { get; set; }
    }
}
